package com.ldb.Controller;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.cfg.beanvalidation.ActivationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ldb.Controller.entity.Activity;
import com.ldb.Controller.entity.Admin;
import com.ldb.Controller.entity.Messages;
import com.ldb.Controller.entity.Student;
import com.ldb.Controller.service.ActivityManager;
import com.ldb.Controller.service.AdminManager;
import com.ldb.Controller.service.MessagesManager;

@Controller
//@SessionAttributes("admin")
public class HomeController {
	//图片基本地址，需要更改，因为时物理地址
	public static final String ImagePathBase = "/Users/chengliangyao/apache-tomcat-7/webapps/SSH2/WebContent/images";
	
	@RequestMapping("culture")
	public String toCulture() {
		return "culture";
	}

	@Resource(name="ActivityManager")
	private ActivityManager activityManger;
	
	@RequestMapping("/")
	public String index() {
		System.out.println("index");
		return "index";
	}
	
	@RequestMapping("/index")
	public String indexAction() {
		return "index";
	}
	
	@Resource(name="messagesManager")
	private MessagesManager messagesManager;
	
	@RequestMapping("/toMessages")
	public String toMessages() {
		return "/showMessages";
	}
	
	@RequestMapping("/leaveMessage")
	/*
	 * 前台留言
	 */
	public String leaveMessage(Messages message,Map<String,String> map) {
		
		if(message.getTitle() == null || message.getTitle().equals("") || message.getContents() == null || message.getContents().equals("")) {
			map.put("message", "标题和内容不能为空");
			return "leaveMessage";
		}
		
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time = c.getTime();
		message.setTime(df.format(time));
		message.setTimeStamp(time);
		
		if(message.getName() == null || message.getName() == "") {
			message.setName("匿名留言");
		}
		
		this.messagesManager.addAMessage(message);
		return "redirect:/showMessages";
	}
	
	@RequestMapping("/showMessages")
	/*
	 * 前端展示所有留言
	 */
	public String showMessages(Map<String,Object> map) {
		List<Messages> messagesList = this.messagesManager.getAllMessagesDesc();
		map.put("messagesList", messagesList);
		return "/showMessages";
	}
	
	@RequestMapping("/admin_showMessages")
    /*
     * 后台显示所有留言
     */
	public String adminShowMessages(Map<String,Object> map) {
		List<Messages> messagesList = this.messagesManager.getAllMessagesDesc();
		map.put("messagesList", messagesList);
		return "/admin_showMessages";
	}
	
	@RequestMapping("findByPage")
	public void findByPage() {
		
	}
	
	@RequestMapping("/deleteMessage")
	public String deleteMessage(String messageId) {
		this.messagesManager.deleteAMessage(messageId);
		return "redirect:/admin_showMessages";
	}
	
	@Resource(name="ActivityManager")
	public ActivityManager activityManager;
	
	@RequestMapping("/toActivity")
	public String toActivity() {
		return "redirect:/showActivity";
	}
	
	@RequestMapping("/toaddActivity")
	public String toAddActivity(Activity activity){
		return "addActivity";
	}
	
	
	@RequestMapping(value ="/addatimage")
	public String addImage(@RequestParam(value ="file") MultipartFile file, HttpServletRequest request, ModelMap model) {  
       // String path = request.getSession().getServletContext().getRealPath("/images/student");
        String  path = this.ImagePathBase+"/activity/";
        String fileName = file.getOriginalFilename();  
        File targetFile = new File(path, fileName);  
        //保存  
        try {  
            file.transferTo(targetFile);  
            System.out.println(path);
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        model.addAttribute("fileUrl", "./images/activity/"+fileName);  
        return "saveactivityimage";
    } 
	@RequestMapping("/addActivity")
	/*
	 * 后台发布活动
	 */
	public String addActivity(Activity activity,Map<String,String> map){
		if(activity.getTitle() == null || activity.getTexts() ==null || activity.getTitle().equals("") || activity.getTexts().equals("")) {
			map.put("message","标题和内容都不能为空！");
			return "/addActivity";
		}
		if(activity.getImageUrl() !=null && !activity.getImageUrl().equals("")) {
			activity.setImageUrl(activity.getImageUrl());
		}else{
			activity.setImageUrl("");
		}
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time = c.getTime();
		activity.setTime(df.format(time));
		activity.setTimeStamp(time);
		this.activityManager.addActivity(activity);
		map.put("message", "活动发布成功");
		return "/addActivity";
	}
	
	@RequestMapping("/deleteActivity")
	/*
	 * 删除活动信息
	 */
	public String deleteActivity(String messageId) {
		this.activityManager.deleteActivity(messageId);
		return "redirect:/admin_allActivity";
	}
	
	@RequestMapping("/editActivity")
	/*
	 * 编辑活动信息
	 */
	public String editActivity(String activity_id,Map<String,Object> map) {
		Activity activity = this.activityManager.getActivityById(activity_id);
		map.put("activity", activity);
		return "editActivity";
	}
	
	@RequestMapping("/updateActivity")
	/*
	 * 提交修改活动信息
	 */
	public String updateActivity(Activity activity,Map<String,String> map) {
		if(activity.getTitle() == null || activity.getTexts() ==null || activity.getTitle().equals("") || activity.getTexts().equals("")) {
			map.put("message","标题和内容都不能为空！");
			return "/addActivity";
		}
		if(activity.getImageUrl() !=null && !activity.getImageUrl().equals("")) {
			activity.setImageUrl(activity.getImageUrl());
		}else{
			activity.setImageUrl("");
		}
//		Calendar c = Calendar.getInstance();
//		c.setTimeInMillis(System.currentTimeMillis());
//		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Date time = c.getTime();
//		activity.setTime(df.format(time));
//		activity.setTimeStamp(time);
		this.activityManager.updateActivity(activity.getActivity_id(),activity);
		map.put("message", "活动编辑成功");
		return "/editActivity";
	}
	
	@RequestMapping("/showActivity")
	public String getActivityALl(Map<String,Object> map) {
		List<Activity> activityList = this.activityManager.getActivityDesc();
		map.put("activityList", activityList);
		return "/showActivity";
	}
	
	@RequestMapping("/admin_allActivity")
	/*
	 * 后台显示所有活动
	 */
	public String adminAllActivity(String name,Map<String,Object> map) {
		if(name!=null && name =="") {
			map.put("errMessage", "输入为空！");
			return "admin_allActivity";
		}else if(name != null && name != "") {
			List<Activity> activitylist = this.activityManager.getActivityByTitle(name);
			map.put("activityList", activitylist);
			return "admin_allActivity";
		}
		List<Activity> activityList = this.activityManager.getActivityDesc();
		map.put("activityList", activityList);
		return "/admin_allActivity";
	}
	
	@RequestMapping("/toAdminLogin")
	public String toAdminLogin() {
		return "adminLogin";
	}
	
	@Resource(name="adminManager")
	private AdminManager adminManager;
	
	@RequestMapping("/searchAdmin")
	/*
	 * ajax查询管理员是否存在
	 */
	public void searchAdmin(String adminName,HttpServletResponse response) {
		Admin admin = this.adminManager.getAdminByName(adminName);
		if(admin==null) {
			try {
		        //设置页面不缓存
		        response.setContentType("application/json");
		        response.setHeader("Pragma", "No-cache");
		        response.setHeader("Cache-Control", "no-cache");
		        response.setCharacterEncoding("UTF-8");
		        PrintWriter out= null;
		        out = response.getWriter();
		        out.print("该用户不存在");
		        out.flush();
		        out.close();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		}else {
			try {
		        //设置页面不缓存
		        response.setContentType("application/json");
		        response.setHeader("Pragma", "No-cache");
		        response.setHeader("Cache-Control", "no-cache");
		        response.setCharacterEncoding("UTF-8");
		        PrintWriter out= null;
		        out = response.getWriter();
		        out.print("该用户存在");
		        out.flush();
		        out.close();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		}
	}
	
	@RequestMapping(value="/adminLogin")
	/*
	 * 登录
	 */
	public String adminLogin(Admin admins,Map<String,String> map,Model model,HttpServletRequest request,HttpSession session) {
		if(admins.getAdminName()==null || admins.getAdminName()=="" || admins.getPassword() == null || admins.getPassword()=="") {
			map.put("error", "输入不能为空");
			return "adminLogin";
		}
		Admin adminSearch = this.adminManager.getAdminByName(admins.getAdminName());
		if(adminSearch==null) {
			map.put("error", "用户名或者密码错误");
			return "adminLogin";
		}
		Admin result = this.adminManager.getAdminByName(admins.getAdminName());
		if(!result.getPassword().equals(admins.getPassword())) {
			map.put("error", "密码错误，请重试！");
			return "adminLogin";
		}else {
			String adminName = adminSearch.getAdminName();
			model.addAttribute("admin", adminName);
			return "adminIndex";
		}
	}
	
	@RequestMapping("/logout")
	/*
	 * 退出
	 */
	public String logout(Model model,HttpSession session) {
		model.addAttribute("admin", "");
		return "adminLogin";
	}
	
	@RequestMapping("/toAdmin")
	public String toAdmin(Map<String,String> map,Model model,HttpSession session) {
		map.put("admin", session.getAttribute("admin").toString());
		return "adminIndex";
	}
}
